var gmap, geo, gmap_first = true, gmap_opt;
//var gmap_center = new google.maps.LatLng(22.9986009, 120.21844310000006);
var gmap_center = new google.maps.LatLng(22.641996, 120.31684900000005);
var gmaph, gmaph_first = true;
var markers = [], gmapinfowin;
var geo_flag = {}, latlngmap = {};
var hmap, hmap_data_count = {}, hmap_data_money = {};
var prevDate = null;
var date_sep = '-';
var tbl;
var hmap_type = 'freq';
var max_count, max_money;
var addr_count = {}, addr_money = {};

function ajax(func)//{{{
{
	$.ajax({
		type: "POST",
		url: "ajax1",
		data: {in2: $("[name=in2]").val()},
		success: func(msg)
	});
	return;
}//}}}
function ajax_insc(name, func)//{{{
{
	$.ajax({
		type: "POST",
		url: "/ajax_insc",
		data: {
			"name": name
		},
		success: function(response) {//{{{
			var ret = JSON.parse(response);

			if (ret.ret)//{{{
			{
				$.each($("#in-cat").children().get().reverse(), function(k, obj) {
					if (name > $(obj).val())
					{
						$(obj).after('<option value="' + name + '">' + name + '</option>\n');
						return false;
					}
				});
			}//}}}
		}//}}}
	});
	return;
}//}}}
function ajax_inse(date, item, val, cat, loc, comment, geodata)//{{{
{
	var data = {
		"date": date,
		"item": item,
		"val": val,
		"cat": cat,
		"loc": loc,
		"comment": comment
	};
	if (arguments.length > 6)
	{
		data.formatted_addr = geodata.formatted_addr;
		data.lat = geodata.lat;
		data.lng = geodata.lng;
	}
	console.log('data is', data);
	$.ajax({
		type: "POST",
		url: "/ajax_inse",
		data: data,
		success: function(response) {
			var ret = JSON.parse(response);

			if (ret.ret)//{{{
			{
				tbl.fnAddData([
					date,
					item,
					val,
					cat,
					loc,
					comment,
					ret.id
				]);
				tbl.$("tr").click(function() {
					$(this).toggleClass('row_selected');
					if (tbl.$('tr.row_selected').length > 0)
						$("#btn_del").button('enable');
					else
						$("#btn_del").button('disable');
				});
			}//}}}
		}
	});
	return;
}//}}}
function ajax_dele(data, row, func)//{{{
{
	$.ajax({
		type: "POST",
		url: "/ajax_dele",
		data: {
			"id": data[6]
		},
		success: function(response) {//{{{
			var ret = JSON.parse(response);

			if (ret.ret)
			{
				func(row);
				refresh_markers(gmap);
			}
		}//}}}
	});
	return;
}//}}}
function gmap_init()//{{{
{
	geo = new google.maps.Geocoder();
	gmap_opt = {
		//台南市大學路1號
		center: gmap_center,
		zoom: 16,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	gmap = new google.maps.Map(document.getElementById('map_canvas'), gmap_opt);
	$("#map_canvas").height($(window).height() * 0.77);

	$("#heatmap_canvas").height($(window).height() * 0.77);
	gmapinfowin = new google.maps.InfoWindow();
	return;
}//}}}
function addMarker(map, loc, title, content)//{{{
{
	var marker = new google.maps.Marker({
		position: loc,
		map: map,
		title: title
	});
	markers.push(marker);
	google.maps.event.addListener(marker, 'click', function() {
		gmapinfowin.setContent('<div class="infowindow">' + content + '</div>');
		gmapinfowin.open(map, marker);
	});
	return;
}//}}}
function getLatLng(addr, func)//{{{
{
	if (latlngmap[addr])
	{
		console.log(addr, 'already in mapping');
		return;
	}
	geo.geocode({"address": addr, "region": "tw"}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK)
		{
			addLatlng(addr, results[0]);
			//latlngmap[addr] = results[0];
		}
		else
			alert("Geocode was not successful for the following reason: " + status);
	});
}//}}}
function checkRegexp(obj, pat, msg)//{{{
{
	if (!pat.test(obj.val()))
	{
		var info = $("#addent-info");
		obj.addClass('ui-state-error');
		info.text(msg).addClass('ui-state-highlight');
		setTimeout(function() {
			info.removeClass('ui-state-highlight', 1500);
		}, 500);
		return false;
	}
	if (obj.hasClass('ui-state-error'))
		obj.removeClass('ui-state-error');
	//alert('valid check of ' + obj.attr('id'));
	return true;
}//}}}
function refresh_markers(map)//{{{
{
	//clear exist markers
	$.each(markers, function(k, marker) {
		marker.setMap(null);
	});
	markers.length = 0;
	
	//re-add markers
	var infowin_contents = {};
	$.each(tbl._('tr', {"filter": "applied"}), function(k, data) {//{{{
		var addr = data[4];
		
		if (!infowin_contents[addr])
			infowin_contents[addr] = '';
		infowin_contents[addr] += '<p>' + data[0] + ' ' + data[1] + ' $' + data[2] + '</p>\n';
	});//}}}
	$.each(infowin_contents, function(addr, content) {//{{{
		if (latlngmap[addr])
			addMarker(map, tolatlng(latlngmap[addr]), addr, content);
		else//{{{
		{
			geo.geocode({"address": addr, "region": "tw"}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK)
				{
					var loc = results[0].geometry.location;
					addLatlng(addr, results[0]);
					//latlngmap[addr] = results[0];
					addMarker(map, latlngmap[addr], addr, content);
				}
			});
		}//}}}
	});//}}}
	return;
}//}}}
function proc_hmap_data(addr, loc, count, money)//{{{
{
	var data = {
		"lat": loc.lat(),
		"lng": loc.lng(),
	};
	if (count > max_count)
		max_count = count;
	data.count = count;
	hmap_data_count.data.push(data);
	if (money > max_money)
		max_money = money;
	data.count = money
	hmap_data_money.data.push(data);
	addMarker(gmap, loc, addr, infowin_contents[addr]);
	return;
}//}}}
function addLatlng(addr, geores)//{{{
{
	latlngmap[addr] = {};
	latlngmap[addr].formatted_addr = geores.formatted_address;
	latlngmap[addr].lat = geores.geometry.location.lat();
	latlngmap[addr].lng = geores.geometry.location.lng();
	return;
}//}}}
function tolatlng(obj)//{{{
{
	return new google.maps.LatLng(obj.lat, obj.lng);
}//}}}
function init()//{{{
{
	tbl = $("#table1").dataTable({//{{{
		"sScrollY": $(window).height() * 0.7 + "px",
		"bPaginate": false,
		"bScrollCollapse": true,
		"bInfo": false,
		"fnDrawCallback": function() {
			//clear exist markers
			$.each(markers, function(k, marker) {
				marker.setMap(null);
			});
			markers.length = 0;

			addr_count = {};
			addr_money = {};
			var infowin_contents = {};
			$.each(this._('tr', {"filter": 'applied'}), function(k, data) {//{{{
				var addr = data[4];

				if ($.trim(data[4]).length <= 0)
					return;

				if (!addr_count[addr])
					addr_count[addr] = 1;
				else
					addr_count[addr] += 1;

				if (!addr_money[addr])
					addr_money[addr] = parseInt(data[2]);
				else
					addr_money[addr] += parseInt(data[2]);

				if (!infowin_contents[addr])
					infowin_contents[addr] = '';
				infowin_contents[data[4]] += '<p>' + data[0] + ' ' + data[1] + ' $' + data[2] + '</p>\n';
				//console.log(gmap, latlngmap[data[4]].geometry.location, data[4], data[0] + ' ' + data[1] + ' $' + data[2]);
			});//}}}
			max_count = 0;
			max_money = 0;
			hmap_data_count.data = [];
			hmap_data_money.data = [];
			$.each(addr_count, function(addr, count) {
				if (latlngmap[addr])//{{{
				{
					var loc = tolatlng(latlngmap[addr]);
					var data = {
						"lat": loc.lat(),
						"lng": loc.lng(),
						"count": count
					};
					var data2 = $.extend(true, {}, data);
					if (count > max_count)
						max_count = count;
					if (addr_money[addr] > max_money)
						max_money = addr_money[addr];
					hmap_data_count.data.push(data);

					data2.count = addr_money[addr];
					hmap_data_money.data.push(data2);
					addMarker(gmap, loc, addr, infowin_contents[addr]);
				}//}}}
				else//{{{
				{
					console.log('something is wrong here~');
					geo.geocode({"address": addr, "region": "tw"}, function(results, status) {
						if (status == google.maps.GeocoderStatus.OK)
						{
							var loc = results[0].geometry.location;
							addLatlng(addr, results[0]);
							//latlngmap[addr] = results[0];
							//console.log('geocoded', addr, loc.lat(), loc.lng(), count);
						}
					});
				}//}}}
			});
			hmap_data_count.max = max_count / 2;
			hmap_data_money.max = max_money / 2;
			if (hmap)
			{
				if (hmap_type == 'freq')
					hmap.setDataSet(hmap_data_count);
				else if (hmap_type == 'money')
					hmap.setDataSet(hmap_data_money);
				hmap.draw();
			}
		}
	});//}}}
	$("#main").tabs({//{{{
		show: function(event, ui) {
			if (ui.panel.id == 'tab-map')//{{{
			{
				if (gmap_first)
				{
					gmap_first = false;
					google.maps.event.trigger(gmap, 'resize');
					gmap.setCenter(gmap_center);
				}
			}//}}}
			else if (ui.panel.id == 'tab-heatmap')//{{{
			{
				if (gmaph_first)
				{
					gmaph_first = false;
					gmaph = new google.maps.Map(
						document.getElementById('heatmap_canvas'),
						{
							"center": gmap_center,
							"zoom": 15,
							"mapTypeId": google.maps.MapTypeId.ROADMAP
					});
					hmap = new HeatmapOverlay(gmaph, {
						"radius": 15,
						"visible": true,
						"opacity": 75
					});
					setTimeout(function() {
						if (hmap_type == 'freq')
							hmap.setDataSet(hmap_data_count);
						else
							hmap.setDataSet(hmap_data_money);
						hmap.draw();
					}, 250);
				}
			}//}}}
			else if (ui.panel.id == 'tab-list')
				tbl.fnDraw();
		}
	});//}}}
	tbl.$("tr").click(function() {//{{{
		$(this).toggleClass('row_selected');
		if (tbl.$('tr.row_selected').length > 0)
			$("#btn_del").button('enable');
		else
			$("#btn_del").button('disable');
	});//}}}
	tbl.fnSetColumnVis(6, false);
	$("#dialog-confirm-delete").dialog({//{{{
		autoOpen: false,
		modal: true,
		buttons: {
			"Delete selected": function() {
				tbl.$('tr.row_selected').each(function() {
					var data = tbl.fnGetData(this);
					ajax_dele(data, this, function(row) {tbl.fnDeleteRow(row);});
				});
				$(this).dialog('close');
			},
			"Cancel": function() {
				$(this).dialog('close');
			}
		}
	});//}}}
	$("#table1_filter").append(//{{{
		$('<button id="btn_del">Delete selected rows</button>').button({
			icons: {primary: "ui-icon-closethick"},
			text: false,
			disabled: true
		}).click(function() {
			if (tbl.$('tr.row_selected').length > 0)
				$("#dialog-confirm-delete").dialog('open');
		})
	);//}}}
	var date = new Date();
	var date_pat = date.getFullYear() + date_sep + (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + date_sep;
	tbl.fnFilter(date_pat, 0);
	$("#datepick").datepicker({//{{{
		onSelect: function(dateText, inst)
		{
			if (dateText == prevDate)
			{
				prevDate = null;
				$('#datepick').datepicker('setDate', null);
				tbl.fnFilter(dateText.substring(0, dateText.length - 2), 0);
			}
			else
			{
				prevDate = dateText;
				tbl.fnFilter(dateText, 0);
			}
			tbl.fnDraw();
		},
		dateFormat: "yy-mm-dd",
		onChangeMonthYear: function(year, month, inst) {
			var date_pat = year + date_sep + (month < 10 ? '0' + month : month) + date_sep;
			tbl.fnFilter(date_pat, 0);
			tbl.fnDraw();
		}
	});//}}}
	$("#dialog-addent").dialog({//{{{
		autoOpen: false,
		modal: true,
		buttons: {
			"Add new entry": function() {
				var date = $("#in-date"), item = $("#in-item"), val = $("#in-val"), cat = $("#in-cat"), loc = $("#in-loc"), cmt = $("#in-comment");
				var vals = [date, item, val, cat, loc, cmt];
				var valid = false;
				
				valid = checkRegexp(item, /.+/, 'Item must not be empty')
				valid = valid && checkRegexp(date, /\d+[^\d]\d{1,2}[^\d]\d{1,2}/, 'Date must be of the format "yyyy-mm-dd"')
				valid = valid && checkRegexp(val, /\d+/, 'Value must be integer');
				if (valid)
				{
					if (!latlngmap[loc.val()])
						geo.geocode({"address": loc.val(), "region": "tw"}, function(results, status) {
							if (status == google.maps.GeocoderStatus.OK)
							{
								addLatlng(loc.val(), results[0]);
								ajax_inse(date.val(), item.val(), val.val(), cat.val(), loc.val(), cmt.val(), latlngmap[loc.val()]);
							}
						});
					else
						ajax_inse(date.val(), item.val(), val.val(), cat.val(), loc.val(), cmt.val());
					$(this).dialog("close");
					//vals.map(function(v) {v.val('');});
				}
			},
			Cancel: function() {$(this).dialog("close");}
		},
		close: function() {
			//[$("#in-date"), $("#in-item"), $("#in-val"), $("#in-cat"), $("#in-loc"), $("#in-comment")].map(function(v) {v.val('');});
		}
	});//}}}
	$("#dialog-addcat").dialog({//{{{
		autoOpen: false,
		modal: true,
		buttons: {
			"Create": function() {
				var catname = $("#cat-name"), info = $("#addcat-info");
				var valid = false;

				name = $.trim(catname.val());
				if (name.length <= 0)//{{{
				{
					info.text('Name must have lenth greater than 0').addClass('ui-state-highlight');
					setTimeout(function() {
						info.removeClass('ui-state-highlight', 1500);
					}, 500);
					catname.addClass('ui-state-error');
					return;
				}//}}}
				if ($.inArray(name, cats) >= 0)//{{{
				{
					$("#addcat-info").text('Category already exists').addClass('ui-state-highlight');
					setTimeout(function() {
						info.removeClass('ui-state-highlight', 1500);
					}, 500);
					if (!catname.hasClass('ui-state-error'))
						catname.addClass('ui-state-error');
					return;
				}
				else
				{
					if (catname.hasClass('ui-state-error'))
						catname.removeClass('ui-state-error');
					valid = true;
				}//}}}
				if (valid)
				{
					ajax_insc(name);
					cats.push(name);
					$(this).dialog('close');
				}
			},
			"Cancel": function() {$(this).dialog('close');}
		}
	});//}}}
	$("body").fadeIn();
	tbl.fnDraw();
	//input autocomplete//{{{
	$("#in-item").autocomplete({
		source: itemcomp,
		minLength: 0
	}).click(function() {
		$(this).autocomplete('search', '');
	});
	$("#in-date").datepicker({dateFormat: "yy-mm-dd"});
	$("#in-loc").autocomplete({
		source: addrcomp,
		minLength: 0
	}).click(function() {
		$(this).autocomplete('search', '');
	});
	$("#in-comment").autocomplete({
		source: cmtcomp,
		minLength: 0
	}).click(function() {
		$(this).autocomplete('search', '');
	});//}}}
	$("#table_cur_month").button().click(function() {//{{{
		var date = new Date();
		var date_pat = date.getFullYear() + date_sep + (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + date_sep;
		tbl.fnFilter(date_pat, 0);
	});//}}}
	$("#table_full").button().click(function() {//{{{
		tbl.fnFilter('', 0);
	});//}}}
	$("#addent").button().click(//{{{
		function() {$("#dialog-addent").dialog("open");}
	);//}}}
	$("#dialog-addcat").keydown(function(event) {//{{{
		if (event.keyCode == 13)
			$(this).parent().find("button:eq(0)").trigger("click");
	});//}}}
	$("#dialog-addent").keydown(function(event) {//{{{
		if (event.keyCode == 13)
			$(this).parent().find("button:eq(0)").trigger("click");
	});//}}}
	$("#addcat").button({disabled: false}).click(//{{{
		function() {$("#dialog-addcat").dialog("open");}
	);//}}}
	$("#hmap_toggle").button().click(function() {//{{{
		if (hmap_type == 'freq')
		{
			hmap_type = 'money';
			hmap.setDataSet(hmap_data_money);
		}
		else
		{
			hmap_type = 'freq';
			hmap.setDataSet(hmap_data_count);
		}
		hmap.draw();
	});//}}}
	return;
}//}}}
function drawChart()//{{{
{
	for (var i in stats)
	{
		var data = new google.visualization.DataTable();
		var title = null;

		data.addColumn('string', 'category');
		data.addColumn('number', 'total');
		for (var j in stats[i])
		{
			if (stats[i][j][0] == "yearmonth")
				title = stats[i][j][1];
			else if (stats[i][j][0] == "")
				data.addRows([['Uncategorized', stats[i][j][1]]]);
			else
				data.addRows([stats[i][j]]);
		}
		if (title)
		{
			var div = $(document.createElement('div')).css('display', 'inline').css('float', 'left');
			$("#tab-stat").append(div);
			width_mul = 0.35;
			if (screen.width < 1440)
				width_mul = 0.32;
			new google.visualization.PieChart(div[0]).draw(data, {title: title, width: $(document).width() * width_mul, height: $(document).width() * 0.2, fontSize: 12});
		}
	}
	return;
}//}}}
//archived//{{{
/*
$("#drag1").draggable();
$("#drop1").droppable({
	tolerance: "touch",
	drop: function(e, ui) {
		$(this).css("background-color", "green");
		$(this).find("p").html("dropped on!");
	},
	out: function(e, ui) {
		$(this).css("background-color", "grey");
		$(this).find("p").html("drop zone");
	}
});*///}}}
